package com.quectel.cms.controller.grid;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.grid.dto.GridDto;
import com.quectel.core.module.grid.dto.GridEventDiscoveryBindingDto;
import com.quectel.core.module.grid.service.GridEventDiscoveryBindingService;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.sys.module.sys.dto.SysCodeDto;
import com.quectel.sys.module.sys.service.SysCodeService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/02/03 15:45
 */
@RestController
@RequestMapping("gridEventDiscoveryBinding")
@Tag(name = "GridEventDiscoveryBindingController", description = "网格智能发现事件类型绑定关系表相关api")
public class GridEventDiscoveryBindingController extends BaseController {

    @DubboReference
    private GridEventDiscoveryBindingService gridEventDiscoveryBindingService;
    @DubboReference
    private GridService gridService;
    @DubboReference
    private SysCodeService sysCodeService;

    /**
     * 查询出没有被绑定的
     *
     * @return
     */
    @GetMapping("queryEventType")
    @Operation(summary = "查询事件类型列表")
    public Response<List<SysCodeDto>> queryEventType() {
        List<SysCodeDto> list = sysCodeService.queryListByMark(SysCodeKeyConstants.EVENT_TYPE);
        return Response.<List<SysCodeDto>>ok().wrap(list);
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("gridList")
    @Operation(summary = "根据条件查询网格列表")
    public Response<Page<GridDto>> gridList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = gridService.queryTotal(request.getParams());

        List<GridDto> list = null;
        if (total > 0) {
            list = gridService.queryList(request.getParams());
            for (int i = 0; i < list.size(); i++) {
                GridDto gridDto = list.get(i);
                Map<String, Object> queryMap = new HashMap<>();
                queryMap.put(LambdaUtil.getFieldName(GridEventDiscoveryBindingDto::getGridId), gridDto.getId());
                int queryTotal = gridEventDiscoveryBindingService.queryTotal(queryMap);
                if (queryTotal > 0) {
                    gridDto.setEventCount(queryTotal);
                } else {
                    gridDto.setEventCount(0);
                }
            }
        } else {
            list = new ArrayList<>();
        }

        Page<GridDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridDto>>ok().wrap(page);
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "gridEventDiscoveryBinding:list")
    @Operation(summary = "网格智能发现事件类型绑定关系的分页查询列表")
    public Response<Page<GridEventDiscoveryBindingDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = gridEventDiscoveryBindingService.queryTotal(request.getParams());

        List<GridEventDiscoveryBindingDto> list = null;
        if (total > 0) {
            list = gridEventDiscoveryBindingService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<GridEventDiscoveryBindingDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridEventDiscoveryBindingDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "gridEventDiscoveryBinding:edit")
    @Operation(summary = "查询单条网格智能发现事件类型绑定关系记录")
    public Response<GridDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        GridDto gridDto = gridService.selectById(id);
        return Response.<GridDto>ok().wrap(gridDto);
    }

    /**
     * 通过网格id查询绑定的智能发现类型
     *
     * @param gridId
     * @return
     */
    @GetMapping("getBind")
    @Operation(summary = "通过网格id查询绑定的智能发现类型")
    public Response<List<SysCodeDto>> getBind(@RequestParam(required = false) Long gridId) {

        List<SysCodeDto> result = new ArrayList<>();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(LambdaUtil.getFieldName(GridEventDiscoveryBindingDto::getGridId), gridId);
        List<GridEventDiscoveryBindingDto> bindCategory = gridEventDiscoveryBindingService.queryList(queryMap);
        for (GridEventDiscoveryBindingDto bindingDto : bindCategory) {
            SysCodeDto sysCodeDto = sysCodeService.selectOneWithMarkValue(SysCodeKeyConstants.EVENT_TYPE, bindingDto.getCategory() + "");
            result.add(sysCodeDto);
        }
        return Response.<List<SysCodeDto>>ok().wrap(result);
    }


    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "gridEventDiscoveryBinding:info")
    @Operation(summary = "查询单条网格智能发现事件类型绑定关系记录")
    public Response<GridEventDiscoveryBindingDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridEventDiscoveryBindingDto gridEventDiscoveryBindingDto = gridEventDiscoveryBindingService.selectById(id);

        return Response.<GridEventDiscoveryBindingDto>ok().wrap(gridEventDiscoveryBindingDto);
    }

    /**
     * 保存
     *
     * @param gridEventDiscoveryBindingDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "gridEventDiscoveryBinding:edit")
    @Operation(summary = "保存单条网格智能发现事件类型绑定关系记录")
    public Response<Object> save(@RequestBody @Validated GridEventDiscoveryBindingDto gridEventDiscoveryBindingDto) {

        //填充基础数据
        fillSaveCommonData(gridEventDiscoveryBindingDto);

        gridEventDiscoveryBindingService.saveOrUpdate(gridEventDiscoveryBindingDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "gridEventDiscoveryBinding:edit")
    @Operation(summary = "修改单条网格智能发现事件类型绑定关系记录")
    public Response<Object> update(@RequestBody @Validated GridEventDiscoveryBindingDto vo) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        gridEventDiscoveryBindingService.saveOrUpdate(vo);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "gridEventDiscoveryBinding:delete")
    @Operation(summary = "批量删除存在的网格智能发现事件类型绑定关系记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (gridEventDiscoveryBindingService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        gridEventDiscoveryBindingService.deleteBatch(ids);

        return Response.ok();
    }
}
